const baseUnit = 100;
var phi = 0;
var camidx = 0;
var uuid = "";
var filepath = "";
var filelist = "";

$(function () {
    balanceColor();//设置余额字体颜色
    var voucherTable = $(".voucherTable");
    const max = 999999999.99;//
    $(window).keydown(function (event) {

        if ((event.which === 83 && event.ctrlKey)){
            console.log ( "Ctrl-s 保存");
            subForm('voucherForm',root+'control/adIndex.html?cla=voucherEdit&fun=editEdit&href=save')
            return false;
        }
        if ((event.altKey && event.which === 78)){
            console.log ( "alt+N 新增");
            location.href=root+'control/adIndex.html?cla=voucherEdit&fun=home';
            return false;
        }

        if ((event.which === 81 && event.ctrlKey)){
            subForm('voucherForm',root+'control/adIndex.html?cla=voucherEdit&fun=editEdit&href=new');
            console.log ( "Ctrl+Q 保存并新增");
            return false;
        }
        if ((event.which === 120)){
            console.log ( "F9 保存并复制");
            subForm('voucherForm',root+'control/adIndex.html?cla=voucherEdit&fun=editEdit&href=copy');
            return false;
        }

    })
    tippy("#shortKey", {
        // default
        trigger: 'click',
        content: '<h4>保存：Ctrl+S</h4><h4>保存并新增：Ctrl+Q</h4><h4>保存并复制：F9</h4><h4>新增：Alt+N</h4><h4>自动平衡借贷方金额：=</h4>',
        allowHTML: true,
    });
    //点击非下拉区域隐藏
    $(document).on('click', function (e) {
        let target = $("#text-btn");
        if (!target.is(e.target) && target.has(e.target).length === 0) {
            $("#text-input").hide();
        }
    });

    $(".next-button,.pre-button").on('click', function () {
        let type = $(this).data('type');
        let id = $(this).data('id');
        $.post(root + 'control/adIndex.html?cla=voucherEdit&fun=showNextVoucher', {type: type, id: id}, function (res) {
            if (res.warn == 2) {
                location.href = res.href;
            } else {
                msg(res.warn, 'error');
            }
        }, 'json')
    })

    //摘要文本补充
    $(".td-data .summary-input").each(function () {
        let _this = $(this);
        $(this).bigAutocomplete({
             sign:'voucherSummary',
            url: root + 'control/adIndex.html?cla=voucherEdit&fun=getSummary',
            callback: function (data, e) {
                $(e).parent().find(".summary").html(data.title);
            }
        });
    })
    //科目补充
    $(".td-data .subject-input").each(function () {
        $(this).bigAutocomplete({
            width: 300,
            url: root + 'control/adIndex.html?cla=voucherEdit&fun=getSubject',
            callback: function (data, e) {
                let mxId = $(e).parent().parent().parent().find("[name='mxId[]']").val();
                $(e).parent().parent().find(".subject-name").html(data.title);
                $(e).parent().parent().find("[name='subjectId[" + mxId + "]']").val(data.id);
                $(e).parent().find(".subject-ico").hide();
                chooseSubject(data.id, mxId);
                $(e).hide();
            }
        });
    })
    //更多选项
    $(".stateBlock li").click(function () {
        showState();
        let name = $(this).text();
        if (name === '使用模板') {
            layer('voucherEdit', 'template', {})
        } else if (name === '存为模板') {
            layer('voucherEdit', 'templateSave', {})
        } else if (name === '选项') {
            layer('voucherEdit', 'voucherNumAdd', {})
        }
    });
    //科目
    voucherTable.on('click', '.subject-content', function () {
        if (!$(this).find(".subject-name").text()) {
            $(this).hide();
            $(this).parent().find(".subject-input").show();
            $(this).parent().find(".subject-ico").show();
            $(this).parent().find(".subject-input").focus();
        }

    })
    voucherTable.on('blur', '.subject-input', function (e) {
        $(this).hide();
        $(this).parent().parent().find(".subject-name").text($(this).val())
        $(this).parent().parent().find(".subject-content").show();

    })
    //点击科目
    voucherTable.on('click', '.subject-name', function () {
        $(this).parent().hide();
        $(this).parent().parent().find(".subject-input").show();
        $(this).parent().parent().find(".subject-input").focus();
        $(this).parent().parent().find(".subject-ico").show();
    });
    //增加，删除图标显示
    voucherTable.on('mouseenter', '.td-data,.add_v_btn,.del_v_btn', function () {
        if ($(this).attr('class') === 'td-data') {
            $(this).find(".add_v_btn,.del_v_btn").show();
        } else {
            $(this).parent().parent().find(".add_v_btn,.del_v_btn").show();
        }
    });
    voucherTable.on('mouseleave', '.td-data,.add_v_btn,.del_v_btn', function () {
        $(".add_v_btn,.del_v_btn").hide();
    });
    voucherTable.on('click', '.add_v_btn', function () {
        let _this = $(this);
        $.post(root + 'control/adIndex.html?cla=voucherEdit&fun=addRow', {}, function (res) {
            _this.parent().parent().after(res.html);
        }, 'json')
    })
    voucherTable.on('click', '.del_v_btn', function () {
        $(this).parent().parent().remove();
    })
    //描述
    voucherTable.off('click','.summary').on('click', '.summary', function () {
        $(this).hide();
        $(this).parent().find(".summary-input").show();
        $(this).parent().find(".summary-input").focus();
    })
    voucherTable.on('blur', '.summary-input', function () {
        $(this).hide();
        $(this).parent().find(".summary").text($(this).val())
        $(this).parent().find(".summary").show();
    })
    //辅助核算
    voucherTable.on('click', '.assist-name', function () {
        let mxId = $(this).parent().parent().parent().find("[name='mxId[]']").val();
        let subjectId = $(this).parent().parent().find("[name='subjectId[" + mxId + "]']").val();
        let khid = $(this).parent().parent().find("[name='khid[" + mxId + "]']").val();
        let supplierId = $(this).parent().parent().find("[name='supplierId[" + mxId + "]']").val();
        let departmentId = $(this).parent().parent().find("[name='departmentId[" + mxId + "]']").val();
        let materialSkuId = $(this).parent().parent().find("[name='materialSkuId[" + mxId + "]']").val();
        let staffId = $(this).parent().parent().find("[name='staffId[" + mxId + "]']").val();
        let cashId = $(this).parent().parent().find("[name='cashId[" + mxId + "]']").val();
        let projectId = $(this).parent().parent().find("[name='projectId[" + mxId + "]']").val();
        layer('voucherEdit', 'assist', {mxId: mxId, subjectId: subjectId,khid:khid,supplierId:supplierId,departmentId:departmentId,materialSkuId:materialSkuId,staffId:staffId,cashId:cashId,projectId:projectId})
    })
    //借
    voucherTable.off('click','.jie').on('click', ".jie", function () {
        let parent = $(this).parent();
        $(this).hide();
        parent.find(".money-input").show();
        parent.find(".money-input").focus();
        parent.find(".jie-input").off('keydown').keydown(function (ev) {
            let _that = $(this);
            if (ev.keyCode === 13) {
                autoAddRow(parent,_that,'借')
            }
            if (ev.keyCode === 187){
                console.log ( "= 自动平衡借贷方金额");
                let daiMoney = 0;
                $(".dai-input").each(function () {
                    daiMoney += Number($(this).val());
                });
                let jieMoney = 0;
                $(".jie-input").each(function () {
                    jieMoney += Number($(this).val());
                });
                let jie =Number(_that.val());
                _that.val(daiMoney-jieMoney+jie);
                parent.find(".jie-text").text(((daiMoney-jieMoney+jie) * baseUnit).toFixed(0))
            }
        });
    })

    voucherTable.on('blur', ".jie-input", function () {
        let money = Number($(this).val());
        if (money > max) {
            msg('金额超过最大限制位数', 'error')
            return false;
        }

        $(this).hide();
        $(this).parent().find(".show_money").show();
        $(this).parent().find(".jie-text").text((money * baseUnit).toFixed(0))
        let daiMoney = Number($(this).parent().next().find(".dai-input").val());
        if (money == 0 && daiMoney != 0) {
            return false;
        }
        $(this).parent().next().find(".dai-text").html('');
        $(this).parent().next().find(".dai-input").val('');
        total_money();
        //计算单价
        let mxId = $(this).parent().parent().find("[name='mxId[]']").val();
        let obj = $("[data-id='" + mxId + "']").parent().parent();
        let num = Number($(this).parent().parent().find("[name='voucherNum[" + mxId + "]']").val());

        if (num > 0) {
            let price = (money / num).toFixed(4);
            $(this).parent().parent().find("[name='voucherPrice[" + mxId + "]']").val(price)
            $(this).parent().parent().find(".voucher-price-text").html(price)
        }
        let subjectId =   obj.find("[name='subjectId[" + mxId + "]']").val();
        culBalance(subjectId,mxId);

    })

    //贷
    voucherTable.off('click','.dai').on('click', ".dai", function () {
        let parent = $(this).parent();
        $(this).hide();
        parent.find(".money-input").show();
        parent.find(".money-input").focus();
        parent.find(".dai-input").off('keydown').keydown(function (ev) {
            let _that = $(this);
            if (ev.keyCode === 13) {
                autoAddRow(parent,_that,'贷')
            }
            if (ev.keyCode === 187){
                console.log ( "= 自动平衡借贷方金额");
                let daiMoney = 0;
                $(".dai-input").each(function () {
                    daiMoney += Number($(this).val());
                });
                let jieMoney = 0;
                $(".jie-input").each(function () {
                    jieMoney += Number($(this).val());
                });
                let dai =Number(_that.val());
                _that.val(jieMoney-daiMoney+dai);
                parent.find(".dai-text").text(((jieMoney-daiMoney+dai) * baseUnit).toFixed(0))
            }
        });
    })
    voucherTable.on('blur', ".dai-input", function () {
        let money = $(this).val();
        if (money > max) {
            msg('金额超过最大限制位数', 'error')
            return false;
        }
        $(this).hide();
        $(this).parent().find(".dai-text").text((money * baseUnit).toFixed(0))
        $(this).parent().find(".show_money").show();
        let jieMoney = Number($(this).parent().prev().find(".jie-input").val());
        if (money == 0 && jieMoney != 0) {
            return false;
        }
        $(this).parent().prev().find(".jie-text").html('');
        $(this).parent().prev().find(".jie-input").val('');
        total_money();
        //计算单价
        let mxId = $(this).parent().parent().find("[name='mxId[]']").val();
        let num = Number($(this).parent().parent().find("[name='voucherNum[" + mxId + "]']").val());
        if (num > 0) {
            let price = (money / num).toFixed(4);
            $(this).parent().parent().find("[name='voucherPrice[" + mxId + "]']").val(price)
            $(this).parent().parent().find(".voucher-price-text").val(price)
        }
        let obj = $("[data-id='" + mxId + "']").parent().parent();
        let subjectId =   obj.find("[name='subjectId[" + mxId + "]']").val();
        culBalance(subjectId,mxId);
    })

    //点击数量
    voucherTable.on('click', ".voucher-num-btn", function () {
        $(this).find(".voucher-num-text").hide();
        $(this).parent().find(".voucher-num-input").show();
        $(this).parent().find(".voucher-num-input").focus();
    })
    //数量输入完毕
    voucherTable.on('blur', ".voucher-num-input", function () {
        $(this).hide();
        $(this).parent().find(".voucher-num-text").text($(this).val())
        $(this).parent().find(".voucher-num-text").show();
        let num = Number($(this).val());//数量
        let price = Number($(this).parent().parent().find(".voucher-price-input").val());//单价
        let money = Number($(this).parent().parent().parent().find(".voucher-money-input").val());//原币
        //计算汇率
        let rate = money > 0 ? (num * price / money).toFixed(4) : 0;
        if (price > 0) {
            $(this).parent().parent().parent().find(".voucher-rate-input").val(rate);
            $(this).parent().parent().parent().find(".voucher-rate-text").html(rate)
            calculateBaseMoney($(this).parent().parent().parent().parent());//计算本位币总金额
        }

    })
    //点击单价
    voucherTable.on('click', ".voucher-price-btn", function () {
        $(this).find(".voucher-price-text").hide();
        $(this).parent().find(".voucher-price-input").show();
        $(this).parent().find(".voucher-price-input").focus();
    })
    //单价输入完毕
    voucherTable.on('blur', ".voucher-price-input", function () {
        $(this).hide();
        $(this).parent().find(".voucher-price-text").text($(this).val())
        $(this).parent().find(".voucher-price-text").show();
        //计算原币
        let price = Number($(this).val());//单价
        let num = Number($(this).parent().parent().find(".voucher-num-input").val());//数量
        let rate = Number($(this).parent().parent().parent().find(".voucher-rate-input").val());//汇率
        let money = rate > 0 ? ((num * price / rate).toFixed(2)) : 0;//原币

        $(this).parent().parent().parent().find(".voucher-money-input").val(money);
        $(this).parent().parent().parent().find(".voucher-money-text").html(money)
        calculateBaseMoney($(this).parent().parent().parent().parent());//计算本位币总金额
    })
    //点击汇率
    voucherTable.on('click', ".voucher-rate-btn", function () {
        $(this).find(".voucher-rate-text").hide();
        $(this).parent().find(".voucher-rate-input").show();
        $(this).parent().find(".voucher-rate-input").focus();
    })
    //汇率输入完毕
    voucherTable.on('blur', ".voucher-rate-input", function () {
        $(this).hide();
        $(this).parent().find(".voucher-rate-text").text($(this).val())
        $(this).parent().find(".voucher-rate-text").show();
        //计算单价
        let num = Number($(this).parent().parent().find(".voucher-num-input").val());//数量
        let rate = Number($(this).parent().parent().find(".voucher-rate-input").val());//汇率
        let money = Number($(this).parent().parent().find(".voucher-money-input").val());//原币
        let price = num > 0 ? (money * rate / num).toFixed(4) : 0
        $(this).parent().parent().find(".voucher-price-input").val(price);
        $(this).parent().parent().find(".voucher-price-text").html(price)
        calculateBaseMoney($(this).parent().parent().parent());//计算本位币总金额
    })
    //点击原币
    voucherTable.on('click', ".voucher-money-btn", function () {
        $(this).find(".voucher-money-text").hide();
        $(this).parent().find(".voucher-money-input").show();
        $(this).parent().find(".voucher-money-input").focus();
    })
    //原币输入完毕
    voucherTable.on('blur', ".voucher-money-input", function () {
        $(this).hide();
        $(this).parent().find(".voucher-money-text").text($(this).val())
        $(this).parent().find(".voucher-money-text").show();
        //计算单价
        let num = Number($(this).parent().parent().find(".voucher-num-input").val());//数量
        let rate = Number($(this).parent().parent().find(".voucher-rate-input").val());//汇率
        let money = Number($(this).parent().parent().find(".voucher-money-input").val());//原币
        let price = num > 0 ? (money * rate / num).toFixed(4) : 0
        $(this).parent().parent().find(".voucher-price-input").val(price);
        $(this).parent().parent().find(".voucher-price-text").html(price)
        calculateBaseMoney($(this).parent().parent().parent());//计算本位币总金额
    })
    $("#text-btn").on('click', function () {
        $("#text-input").show();
    })
    $("#text-input").on('blur', function () {
        $("#text-input").hide();
    })
})

function accountMx(e){
    let parent = $(e).parent().parent().parent().parent();
    let mxId = parent.find("[name='mxId[]']").val();
    let subjectId = parent.find("[name='subjectId["+mxId+"]']").val();
    newIframe('明细账',root+'control/adIndex.html?cla=accountDetails&fun=home&id='+subjectId)

}

/**
 * 根据判断当前借贷行数是否相等从而判断是否需要自动增加行数
 * @param parent
 * @param _that
 * @param direction
 */
function autoAddRow(parent,_that,direction){
    //判断是否需要自动增加1列
    let daiNum = 0;
    let daiMoney = 0;
    $(".dai-input").each(function () {
        if (Number($(this).val())!=0){
            daiNum++;
        }

        daiMoney += Number($(this).val());
    });
    let jieNum = 0;
    let jieMoney = 0;
    $(".jie-input").each(function () {
        if (Number($(this).val())!=0){
            jieNum++;
        }
        jieMoney += Number($(this).val());
    });
    let summary =  parent.parent().find(".summary-input").val();
    if (jieNum != daiNum){
        $.post(root + 'control/adIndex.html?cla=voucherEdit&fun=addRow', {jieNum:jieNum,daiNum:daiNum,jieMoney:jieMoney,daiMoney:daiMoney,direction:direction,summary:summary}, function (res) {
            parent.parent().after(res.html);
            _that.trigger('blur');
        }, 'json')
    }else{
        _that.trigger('blur');
    }
}

//切换凭证字获取当前凭证号
function changeVoucherWordId(e) {
    let voucherWordId = $("[name='voucherWordId']").val();
    let recordDate = $("[name='recordDate']").val();
    $.post(root + 'control/adIndex.html?cla=voucherEdit&fun=getVoucherNo', {
        voucherWordId: voucherWordId,
        recordDate: recordDate
    }, function (res) {
        $("#voucherNo").val(res.voucherNo);
    }, 'json')
}

//获取汇率
function getRate(e) {
    let id = $(e).val();

    $.post(root + 'control/adIndex.html?cla=voucherEdit&fun=getRate', {id: id}, function (res) {
        $(e).parent().parent().parent().find(".voucher-rate-text").text(res.data);
        $(e).parent().parent().parent().find(".voucher-rate-input").val(res.data);
        //计算单价
        let num = Number($(e).parent().parent().parent().find(".voucher-num-input").val());//数量
        let rate = Number(res.data);//汇率
        let money = Number($(e).parent().parent().parent().find(".voucher-money-input").val());//原币
        let price = num > 0 ? (money * rate / num).toFixed(4) : 0
        $(e).parent().parent().parent().find(".voucher-price-input").val(price);
        $(e).parent().parent().parent().find(".voucher-price-text").html(price)
        calculateBaseMoney($(e).parent().parent().parent().parent());//计算本位币总金额
    }, 'json')
}

//合计金额
function total_money() {
    let jieMoney = 0;
    $(".jie-input").each(function () {
        jieMoney += Number($(this).val());
    })
    $(".upper-money-total>span").html(upperMoney(jieMoney))
    $(".jie-total").html((jieMoney * baseUnit).toFixed(0))
    let daiMoney = 0;
    $(".dai-input").each(function () {
        daiMoney += Number($(this).val());
    })
    $(".dai-total").html((daiMoney * baseUnit).toFixed(0))
}

//计算本位币总金额
function calculateBaseMoney(tdObj) {
    let num = Number(tdObj.find(".voucher-num-input").val());//数量
    let price = Number(tdObj.find(".voucher-price-input").val());//单价
    tdObj.parent().find(".jie-text").text((num * price).toFixed(2) * baseUnit);
    tdObj.parent().find(".jie-input").val((num * price).toFixed(2));
    total_money();
}

//辅助核算确认
function confirmAssist(mxId) {

    let str = '';
    let id = '';
    let flag = false;
    let list = 0;
    let objType = '';
    let idArr = [];
    $(".assit-part").each(function (index) {
        id = $(this).data('id')
        if (!id) {
            msg('请选择完辅助核算', 'error');
            flag = true;
            return false;
        }
        if (id) {
            idArr.push(id);
            list++;
            objType = $(this).data('type');
            $("[data-id='" + mxId + "']").parent().parent().find("[name='" + objType + "[" + mxId + "]']").val(id);
            if (index > 0) {
                str += '-';
            }
            str += $(this).val()
        }
    })
    if (flag) {
        return false;
    }
    idArr=idArr.sort();
    let subjectId = $("[data-id='" + mxId + "']").parent().parent().find("[name='subjectId[" + mxId + "]']").val();
    // if (list === 1) {

        // $.post(root + 'control/adIndex.html?cla=voucherEdit&fun=confirmAssist', {
        //     id: id,
        //     objType: objType,
        //     subjectId: subjectId
        // }, function (res) {
        //     $("[data-id='" + mxId + "']").parent().parent().find(".balance-money").html(res.balance);
        // }, 'json')
    // }

    $(".assist-name").show();
    $("[data-id='" + mxId + "']").parent().parent().find(".assist-name").html(str);
    $("[data-id='" + mxId + "']").parent().parent().find(".subject-content").attr('data-asset',idArr.join(','));
    culBalance(subjectId,mxId);
    $('#voucherEditAssist').hide();
}

function chooseTemplate() {
    let templateId = $("form[name='mxForm'] [name='templateId']:checked").val();
    if (!templateId) {
        msg('请选择模板', 'error');
        return false;
    }
    $('#voucherEditTemplate').hide()
    location.href = root + 'control/adIndex.html?cla=voucherEdit&fun=home&method=template&id=' + templateId;
}

function chooseSubjectId(e) {
    let id = $(e).data('id');
    let name = $(e).data('name');
    $(e).parent().find("li").css('background-color', 'white');
    $(e).css('background-color', "rgb(242, 242, 242)");
    $("[name='chooseId']").val(id);
    $("[name='chooseName']").val(name);
}

//获取科目信息
function chooseSubject(id, mxId) {
    subjectRequest(id, mxId);
}

//在弹窗选择科目时确认
function confirmSubjectId(mxId) {
    let id = $("[name='chooseId']").val();
    subjectRequest(id, mxId);
    $('#voucherEditSubject').hide()
}

function subjectRequest(id, mxId) {
    if (!id || !mxId) {
        // msg('未找到ID','error')
        return false;
    }
    let obj = $("[data-id='" + mxId + "']").parent().parent();
    $.post(root + 'control/adIndex.html?cla=voucherEdit&fun=subjectInfo', {id: id}, function (res) {
        if (res.warn == 2) {
            obj.find(".subject-name").html(res.data.code +' '+ res.data.name);
            obj.find(".assist-name").html('');
            obj.find(".voucher-num-text").html('');
            obj.find(".voucher-price-text").html('');
            obj.find("[name='subjectId[" + mxId + "]']").val(res.data.id)
            obj.find("[name='khid[" + mxId + "]']").val('');
            obj.find("[name='voucherPrice[" + mxId + "]']").val('');
            obj.find("[name='supplierId[" + mxId + "]']").val('')
            obj.find("[name='voucherNum[" + mxId + "]']").val('')
            obj.find("[name='staffId[" + mxId + "]']").val('')
            obj.find("[name='projectId[" + mxId + "]']").val('')
            obj.find("[name='materialSkuId[" + mxId + "]']").val('')
            obj.find("[name='cashId[" + mxId + "]']").val('')
            obj.find("[name='departmentId[" + mxId + "]']").val('')

            // obj.find(".balance").show();
            // obj.find(".balance-money").html(res.data.balanceMoney);
            culBalance(id,mxId);
            obj.find(".subject-input").html(res.data.code + res.data.name);
            if (res.data.numAccount === '是') {
                //数量核算
                obj.find(".num-name").show();
            }
            if (res.data.currencyAccount === '是') {
                //外币核算
                let currencyParent = $("[data-id='" + mxId + "']").parent().parent()
                currencyParent.find(".currency-name").show();
                currencyParent.find(".currency-select").empty().append(res.data.currencySelect);
                currencyParent.find(".voucher-rate-text").text(res.data.rate);
                currencyParent.find(".voucher-rate-input").val(res.data.rate);
            }
            if (res.data.assistAccount === '是') {
                let khid = obj.find("[name='khid[" + mxId + "]']").val();
                let supplierId = obj.find("[name='supplierId[" + mxId + "]']").val();
                let departmentId = obj.find("[name='departmentId[" + mxId + "]']").val();
                let materialSkuId = obj.find("[name='materialSkuId[" + mxId + "]']").val();
                let staffId = obj.find("[name='staffId[" + mxId + "]']").val();
                let cashId = obj.find("[name='cashId[" + mxId + "]']").val();
                let projectId = obj.find("[name='projectId[" + mxId + "]']").val();
                layer('voucherEdit', 'assist', {mxId: mxId, subjectId: id,khid:khid,supplierId:supplierId,departmentId:departmentId,materialSkuId:materialSkuId,staffId:staffId,cashId:cashId,projectId:projectId})
            }
        } else {
            msg(res.warn, 'error')
        }
    }, 'json')
}

/**
 * 计算余额
 */
function culBalance(subjectId,mxId){
    if (!subjectId || !mxId) {
        return false;
    }
    let dataIdObj = '';
    let jieMoney=0;
    let daiMoney=0;
    let attrId='';
    let obj = $("[data-id='" + mxId + "']").parent().parent();
    let assetIds = obj.find(".subject-content").attr('data-asset');
    $(".voucherTable input[data-id]").each(function (e) {
        dataIdObj = $(this).parent().parent();
        attrId = dataIdObj.find("[name='mxId[]']").val();
        let attrAssetIds = dataIdObj.find(".subject-content").attr('data-asset');
        if ((dataIdObj.find("[name='subjectId[" + attrId + "]']").val()) === subjectId && assetIds == attrAssetIds){
            //查找相同科目和相同辅助核算ID的项，把金额相加实时算出余额
            jieMoney += Number(dataIdObj.find("[name='jieMoney[" + attrId + "]']").val());
            daiMoney += Number(dataIdObj.find("[name='daiMoney[" + attrId + "]']").val());
        }
    })
    let recordDate = $("[name='recordDate']").val();
    $.post(root + 'control/adIndex.html?cla=voucherEdit&fun=culBalance', {recordDate:recordDate,id: subjectId,mxId:mxId,jieMoney:jieMoney,daiMoney:daiMoney,idCollection:assetIds}, function (res) {
        if (res.warn == 2) {
            $(".voucherTable input[data-id]").each(function (e) {
                dataIdObj = $(this).parent().parent();
                attrId = dataIdObj.find("[name='mxId[]']").val();
                let attrAssetIds = dataIdObj.find(".subject-content").attr('data-asset');
                if ((dataIdObj.find("[name='subjectId[" + attrId + "]']").val()) === subjectId && assetIds == attrAssetIds){
                    dataIdObj.find(".balance").show();
                    dataIdObj.find(".balance-money").html(res.data.balanceMoney);
                }
            })
            balanceColor();
        } else {
            msg(res.warn, 'error')
        }
    }, 'json')
}

function saveFile(formName) {
    let html = '';
    let val = '';
    $("form[name='" + formName + "'] [name='fileId[]']").each(function () {
        val = $(this).val();
        html += "<input name='fileId[]' type='hidden' value='" + val + "'>";
    })
    $("#file-list").empty().append(html);
    $('#voucherEditAttachFile').hide()
}

function voucherNumEdit(form, url) {
    let con = setTimeout(function () {
        $("#loading", parent.document).hide();
    }, 15000);
    $("#loading", parent.document).show();
    //串联表单
    var formName = form.split(",");
    var serialize = "";
    var a = "";
    for (var i = 0; i < formName.length; i++) {
        if (serialize == "") {
            a = "";
        } else {
            a = "&";
        }
        if (formName[i] != "") {
            serialize += a + $("[name=" + formName[i] + "]").serialize();
        }
    }
    //异步提交数据
    $.post(url, serialize, function (data) {
        if (data.warn == 2) {
            $('#voucherEditVoucherNumAdd').hide()
        } else {
            warn(data.warn, 'error');
        }
        $("#loading", parent.document).hide();
        clearTimeout(con);
    }, "json");

}

function commitPhotograph(form, url) {
    let con = setTimeout(function () {
        $("#loading", parent.document).hide();
    }, 15000);
    $("#loading", parent.document).show();
    //串联表单
    var formName = form.split(",");
    var serialize = "";
    var a = "";
    for (var i = 0; i < formName.length; i++) {
        if (serialize == "") {
            a = "";
        } else {
            a = "&";
        }
        if (formName[i] != "") {
            serialize += a + $("[name=" + formName[i] + "]").serialize();
        }
    }
    //异步提交数据
    $.post(url, serialize, function (data) {
        if (data.warn == 2) {
            $('#voucherEditPhotograph').hide();
            $("#file-list").empty().append(data.html);
        } else {
            warn(data.warn, 'error');
        }
        $("#loading", parent.document).hide();
        clearTimeout(con);
    }, "json");
}

//原始文件拍照
function photograph() {
    $('#voucherEditAttachFile').hide()
    layer('voucherEdit', 'photograph', {})
}

function setXformClass() {
    $('.xform').each(function (idx, el) {
        el.className = "xform x" + "-rotated-" + phi;
    });
}

// 旋转
function roateImg() {
    phi = (phi + 90) % 360;
    setXformClass();
    if (phi % 180) {
        $('.xform-p').addClass('rotated');
    } else {
        $('.xform-p').removeClass('rotated');
    }
}

function delImg(e) {
    $(e).parent().remove()
}

//拍照
function GrabImageBase64() {

    var cutpage = document.getElementsByName("cutpage");
    var params = "{\"filepath\":\"base64\",\"rotate\":\"" + phi.toString() + "\",\"camidx\":\"" + camidx.toString() + "\",\"cutpage\":\"" + (cutpage[0].checked ? "1" : "0") + "\"}";//
    var url = "http://127.0.0.1:38088/video=grabimage";
    $.ajax({
        type: "post",
        url: url,
        dataType: "json",
        data: params,
        success: function (data) {
            $(".picture-list").append("<div style='padding:10px;position:relative'><img class='li-ico' style='width:200px' src='data:image/jpg;base64," + data.photoBase64 + "'><a style='position:absolute;top: 2px;right: 72px;' onclick='delImg(this)' href='javascript:void(0)'><div style='top:0;left:0'><span class='u-icon-delete'><i></i></span></div></a><input name='fileCode[]' type='hidden' value='data:image/jpg;base64," + data.photoBase64 + "'></div>")
        }
    });
}

//初始化
function Init() {
    GetResolution();
}

function GetResolution() {
    var params = "{\"type\": \"resolution\",\"camidx\":\"" + camidx.toString() + "\"}";//
    var url = "http://127.0.0.1:38088/param=get";
    $.ajax({
        type: "post",
        url: url,
        dataType: "json",
        data: params,
        success: function (data) {
            if (data.code != 0) {
                console.log("返回代码 = " + data.code + "<br />返回信息 = " + data.message)
            } else {
                var select = document.getElementById("resolution");
                //获取select下拉框下所有的选项
                while (select.options.length > 0) {
                    select.remove(i);
                }

                var arrays = data.resolution.split("|");
                for (var i = 0; i < arrays.length; i++) {
                    select.options.add(new Option(arrays[i], arrays[i]));
                }
            }
        }
    });
}

function showSubjectSelector(e) {
    $(e).hide();
    let id = $(e).parent().parent().parent().find("[name='mxId[]']").val();
    layer('voucherEdit', 'subject', {mxId: id})
}

/**
 * 模板类型编辑
 */
function commitTemp(){
    $.post(root+'control/adIndex.html?cla=voucherEdit&fun=templateTypeEdit',{type:$("[name='typeName']").val()},function (res){
        if (res.warn ===2){
            $('#voucherEditTemplateType').hide();
        }else{
            msg(res.warn,'error')
        }
    },'json')
}

/**
 * 余额为负数时设置自提颜色为红色
 */
function balanceColor(){
    $(".balance-money").each(function () {
        let money = Number($(this).html());
        if (money<0){
            $(this).css('color','red');
        }else{
            $(this).css('color','black');
        }
    })

}